package dao;

import java.sql.*;

public class MyDB {
    private final Connection connection;
    // 数据库配置相关信息
    String DBClass = "com.mysql.cj.jdbc.Driver";
    String MySQLUrl = "jdbc:mysql://127.0.0.1:3307/";
    String DBName = "student";
    String DBParameter = "?useUnicode=true&characterEncoding=utf8&useSSL=false";
    String DBUser = "root";
    String DBPassword = "root";

    public MyDB() {
        try {
            // 加载数据库驱动程序
            Class.forName(DBClass);
            // 创建数据库连接
            connection = DriverManager.getConnection(MySQLUrl + DBName + DBParameter, DBUser, DBPassword);

        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public ResultSet query(String sql) {
        try {
            Statement statement = connection.createStatement();
            return statement.executeQuery(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void update(String sql) {
        try {
            Statement statement = connection.createStatement();
            statement.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public PreparedStatement getPreparedStatement(String sql) {
        try {
            return connection.prepareStatement(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
